<?php
/**
 * Created by PhpStorm.
 * User: DaibiDaddy
 * Date: 2016/5/24
 * Time: 17:14
 */

namespace App\Base;

use BaseExt\Pagination;
use Doctrine\DBAL\Query\QueryBuilder;
use Doctrine\ORM\EntityManager;
use App\Entity\User;
use App\Model\LazyCommon\UserModel;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;

class BaseController4User extends BaseController {

    public $data = [];

    public function __construct()
    {
        parent::__construct();
        $request = Request::createFromGlobals();
        $token = $request->headers->get("token");
        $nowtime = $request->headers->get("nowtime");
        if (md5($nowtime.BaseConfig::__VI__) == $token) {
            die("I KNOW U");
        }

        $data["rnd"] = "?rng=".time();
        $data["curTab"] = 1;
        $data["error"]  = "";
        $data["redirect"] = "";
        $data["delay"] = "0";
        $this->data = $data;
    }

    public function setError($str,$url = "",$delay = 0)
    {
        $this->data["error"] = $str;
        $this->data["redirect"] = $url;
        $this->data["delay"] = $delay;
    }

    /**
     * @param $phone
     * @return User|bool
     */
    public function checkPhoneIsUsed($phone)
    {
        $Model = new UserModel($this->getDoctrine());
        $data = $Model->getByPhone($phone);
        if ($data) {
            //已经注册
            return $data;
        } else {
            //可以使用
            return false;
        }
    }

    public function needToBeLogin()
    {
//        header('content-type:application/json;charset=utf8');
//        $s = 203;
//        $i = "请认证身份";
//        $d = "";
//        $re = array(
//            "s"    => $s,
//            "i"    => $i,
//            "d"    => $d,
//        );
//        die(json_encode($re));
        $url = $this->generateUrl("UserAppHomeIndex");
        header('Location:'.$url);
        die;
    }

    public function isUser()
    {
        $roles = $this->getSessionData("role");
        if (is_array($roles) && in_array("ROLE_USER",$roles)) {
            return $this->getSessionData("id");
        } else {
            return false;
        }
    }

    public function needToBeUser()
    {
        if ($uid = $this->isUser()) {
            return $uid;
        } else {
            $this->needToBeLogin();
        }
    }


    public function getOpenid()
    {
        return $this->getSessionData("openid");
    }

}
